/*
package com.changzhi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.changzhi.common.constans.Constants;
import com.changzhi.common.constans.RedisConstans;
import com.changzhi.common.exception.ServiceException;
import com.changzhi.common.util.DateUtil;
import com.changzhi.ldyl.model.*;
import com.changzhi.ldyl.model.vo.ChristmasRecordVo;
import com.changzhi.ldyl.model.vo.GiftConfigVo;
import com.changzhi.ldyl.model.vo.LotteryVo;
import com.changzhi.mapper.ActivityRecordMapper;
import com.changzhi.mapper.GiftConfigMapper;
import com.changzhi.service.*;
import com.changzhi.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

*/
/**
 * @Description:
 * @author: 小落
 * @date: 2020年12月15日
 *//*

@Slf4j
@Service
public class ChristmasServiceImpl implements ChristmasService {

	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private GiftService giftService;
	@Autowired
	private LotteryService lotteryService;
	@Autowired
	private GiftConfigMapper giftConfigMapper;
	@Resource
	private ActivityRecordMapper activityRecordMapper;
	@Autowired
	private UserService userService;
	@Resource
	private Executor executor;
	public static Map<String, LocalDateTime> TIME_MAP = new HashMap<>();
	public static Map<Integer, String> CHRISTMAS_GIFT_MAP = new HashMap<>();
	public static List<Integer> SHOW_GIFT_LIST = new ArrayList<>();
	private ReentrantLock lock = new ReentrantLock();

	*/
/*//*
/初始化
	@PostConstruct
	public void init(){
		redisUtil.del(RedisConstans.ACTIVITY + 4);
		Activity activity = activityService.getActivity(4);
		//活动时间
		TIME_MAP.put("startTime", activity.getStartTime());
		TIME_MAP.put("endTime", activity.getEndTime());
		//圣诞礼物
		List<GiftConfig> list = giftConfigMapper.selectActivityPrize(Constants.CHRISTMAS_PRIZE);
		for (GiftConfig giftConfig : list) {
			CHRISTMAS_GIFT_MAP.put(giftConfig.getId(), giftConfig.getName());
			//需要展示的礼物
			if(giftConfig.getGiftType() == 1 || giftConfig.getValue() >= 1000){
				SHOW_GIFT_LIST.add(giftConfig.getId());
			}
		}
	}*//*



	@Override
	public void doMqDataByUserGift(UserGift userGift) {
		//是否在活动时间内
		if(!DateUtil.isBetweenTime(TIME_MAP.get("startTime"), TIME_MAP.get("endTime"))){
			return;
		}
		//许愿树许愿的礼物不算在钻石金额计数内
		if(CHRISTMAS_GIFT_MAP.get(userGift.getGiftId()) != null){
			return;
		}
		//处理总值
		Long value = Long.valueOf(userGift.getTotalGiftValue());
		Long cache = (Long) redisUtil.hget(RedisConstans.CHRISTMAS_GIFT, userGift.getUserId());
		if(cache != null){
			value += cache;
		}
		//礼物总值和总抽奖数
		redisUtil.hset(RedisConstans.CHRISTMAS_GIFT, userGift.getUserId(), value, RedisConstans.ONE_MONTH);
	}

	@Override
	public Map<String, Object> lottery(String userId, Integer times){
		if(times == null){
			throw new ServiceException("许愿次数不能为空");
		}
		//加锁保证原子性
		lock.lock();
		Long value = null;
		Integer lotteryCount = null;
		LotteryVo lotteryVo = null;
		try {
			value = (Long) redisUtil.hget(RedisConstans.CHRISTMAS_GIFT, userId);
			lotteryCount = redisUtil.get(RedisConstans.CHRISTMAS_LOTTERY_COUNT + userId);
			lotteryCount = lotteryCount == null ? 0 :lotteryCount;
			value = value == null ? 0 : value;
			if((value / 1000 - lotteryCount) < times){
				throw new ServiceException("许愿数不够");
			}
			//抽奖逻辑
			lotteryVo = lotteryService.lottery(userId, times);
			//记录抽奖次数
			redisUtil.incr(RedisConstans.CHRISTMAS_LOTTERY_COUNT + userId, times);
			redisUtil.expire(RedisConstans.CHRISTMAS_LOTTERY_COUNT + userId, RedisConstans.ONE_MONTH);
		} catch (Exception e) {
			if(!(e instanceof ServiceException)){
				log.error("methodName:lottery,userId={},times={},error={}",userId, times, e.getMessage());
				e.printStackTrace();
			}
			throw e;
		} finally {
			lock.unlock();
		}
		//异步保存奖品
		List<GiftConfig> myPrizes = lotteryVo.getMyPrizes();
		executor.execute(()->{
			for (GiftConfig myPrize : myPrizes) {
				giftService.savePrize(4, userId, myPrize.getId(), null);
			}
			//更新记录缓存
			getRecordByDb();
		});
		//分组统计重复奖品数量
		List<GiftConfigVo> resultList = new ArrayList<>();
		Map<Integer, List<GiftConfig>> groupMap = myPrizes.stream().collect(Collectors.groupingBy(p -> p.getId()));
		for (Integer key : groupMap.keySet()) {
			GiftConfig giftConfig = groupMap.get(key).get(0);
			GiftConfigVo giftConfigVo = new GiftConfigVo();
			giftConfigVo.setId(giftConfig.getId()).setName(giftConfig.getName()).setIcon(giftConfig.getIconUrl()).setNum(groupMap.get(key).size());
			resultList.add(giftConfigVo);
		}
		//返回
		Map<String, Object> map = new HashMap<>();
		map.put("surplus", value / 1000 - lotteryCount - times);
		map.put("prizeList", resultList);
		return map;
	}

	@Override
	public Map<String, Object> surplusLottery(String userId) {
		Long value = (Long) redisUtil.hget(RedisConstans.CHRISTMAS_GIFT, userId);
		Integer lotteryCount = redisUtil.get(RedisConstans.CHRISTMAS_LOTTERY_COUNT + userId);
		value = value == null ? 0 :value;
		lotteryCount = lotteryCount == null ? 0 :lotteryCount;
		Map<String, Object> map = new HashMap<>();
		map.put("surplus", value / 1000 - lotteryCount);
		return map;
	}

	@Override
	public List<ChristmasRecordVo> lotteryRecord() {
		List<ChristmasRecordVo> list = redisUtil.get(RedisConstans.CHRISTMAS_GIFT_LIST);
		if(!CollectionUtils.isEmpty(list)){
			return list;
		}
		return getRecordByDb();
	}

	@Override
	public void fakeRecordData(Map<Integer, List<Integer>> params){
		if(params == null){
			return;
		}
		List<ChristmasRecordVo> resultList = new ArrayList<>();
		int i = 1;
		for(Map.Entry<Integer, List<Integer>> entry : params.entrySet()){
			Integer giftId = entry.getKey();
			List<Integer> accountIdList = entry.getValue();
			for (Integer accountId : accountIdList) {
				//查用户
				User user = userService.getUserByAccountId(accountId);
				if (user == null) {
					continue;
				}
				//查礼物配置
				GiftConfig giftConfig = giftConfigMapper.selectById(giftId);
				if (giftConfig == null) {
					continue;
				}
				//查礼物
				ChristmasRecordVo christmasRecordVo = new ChristmasRecordVo();
				christmasRecordVo.setNickname(user.getNickname())
						.setGiftId(giftId)
						.setUserId(user.getUserId())
						.setGiftName(giftConfig.getName())
						.setId(i++);
				resultList.add(christmasRecordVo);
			}
		}
		Collections.shuffle(resultList);
		Collections.shuffle(resultList);
		redisUtil.set(RedisConstans.CHRISTMAS_GIFT_FAKE_LIST, resultList,RedisConstans.ONE_MONTH);
		//更新缓存
		getRecordByDb();
	}

	private List<ChristmasRecordVo> getRecordByDb(){
		//查真实数据
		LambdaQueryWrapper<ActivityRecord> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(ActivityRecord::getActivityId, 4).in(ActivityRecord::getGiftId, SHOW_GIFT_LIST).orderByDesc(ActivityRecord::getId).last("limit 100");
		List<ChristmasRecordVo> recordList = activityRecordMapper.selectListByChristmas(SHOW_GIFT_LIST);
		//查假数据
		List<ChristmasRecordVo> fakeList = redisUtil.get(RedisConstans.CHRISTMAS_GIFT_FAKE_LIST);
		if(!CollectionUtils.isEmpty(fakeList)){
			recordList.addAll(fakeList);
		}
		redisUtil.set(RedisConstans.CHRISTMAS_GIFT_LIST, recordList, RedisConstans.ONE_DAY);
		return recordList;
	}

}
*/
